<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { Plus } from '@vben/icons';
import { $t } from '@vben/locales';
import { obsUpload, obsDelete, obsDownload } from "#/utils/obs"
import { ElMessage } from 'element-plus';
import type { UploadProps, UploadUserFile } from 'element-plus'

defineOptions({ name: 'UploadIcon' });

// 定义props，接收圆角变量
interface Props {
  borderRadius?: string;
  showBtnTxt?: boolean;
}


const props = withDefaults(defineProps<Props>(), {
  borderRadius: '50%',
  showBtnTxt: false
});

const icon = defineModel<string>('icon', { required: true, default: '' });
const fileList = ref<UploadUserFile[]>([])
const dialogImageUrl = ref('')
const imgVisible = ref(false)

const download = async (templateFile: any) => {
  if (!templateFile) {
    fileList.value = []
    return
  }
  const url = await resDownload(templateFile)
  fileList.value = [
    { url, status: 'success', name: url }
  ] as any
}

const resDownload: any = (templateFile: any) => {
  return new Promise((resolve, reject) => {
    obsDownload({
      Key: templateFile,
      SaveByType: 'file'
    }, (err: any, result: any) => {
      if (err) {
        reject(err)
        return;
      }
      resolve(result?.InterfaceResult.Content.SignedUrl)
    })
  })
}


// 自定义上传方法
const uploadIcon = ({ file }: any) => {
  fileList.value = [
    { url: URL.createObjectURL(file), name: file.name }
  ] as any
  // 上传到 OBS，使用路由路径作为前缀
  obsUpload({
    Key: file.name,
    SourceFile: file
  }, (err: any, result: any, key: string) => {
    if (err) {
      ElMessage.error($t('common.uploadFailTxt'))
      return
    }
    // 上传成功后更新表单数据
    icon.value = key
    ElMessage.success($t('common.uploadSuccessTxt'))
  })

  return Promise.resolve()
}
const handleSuccess = (response: any) => {
  console.log(response)
}
const handleError = (error: any) => {
  console.log(error)
}
const beforeUpload = (file: File) => {
  const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png']
  const isValidFormat = allowedTypes.includes(file.type)
  const isLt5M = file.size / 1024 / 1024 < 5

  if (!isValidFormat) {
    ElMessage.error($t('common.imageFormatTxt'))
    return false
  }
  if (!isLt5M) {
    ElMessage.error($t('common.fileSizeLimitTxt', ['5']))
    return false
  }
  return true
}

const handleExceed = (files: any) => {
  console.log(files)
}
const handleRemove = (file: any) => {
  console.log(file)
  fileList.value = []
  icon.value = ''
  // obsDelete({
  //   Key: icon.value
  // }, (err: any, result: any) => {
  //   if (err) {
  //     ElMessage.error($t('courseMgr.deleteFail'))
  //     return
  //   }
  //   icon.value = ''
  //   ElMessage.success($t('common.deleteSuccessTxt'))
  // })
}

const handlePicturePreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url || ''
  imgVisible.value = true
}

onMounted(() => {
  if (!!icon.value) {
    download(icon.value)
  }
})

// 监听 bannerUrl 变化，重新加载图片
watch(() => icon.value, (newUrl) => {
  if (newUrl && newUrl !== '') {
    download(newUrl)
  } else {
    fileList.value = []
  }
}, { immediate: true })

const emit = defineEmits(['update:modelValue', 'queryData', 'resetQuery']);

</script>
<template>
  <div class="upload-icon h-auto">
    <el-upload :on-preview="handlePicturePreview" class="w-full" action="#" list-type="picture-card"
      :on-success="handleSuccess" :on-error="handleError" :class="{ 'hide-upload-btn': fileList.length > 0 }"
      :before-upload="beforeUpload" :limit="1" :on-exceed="handleExceed" accept="image/png,image/jpeg,image/jpg" :http-request="uploadIcon"
      :file-list="fileList" :auto-upload="true" :on-remove="handleRemove">
      <div class="flex flex-col items-center">
        <Plus class="text-[16px] text-[#595959]" />
        <el-button v-if="props.showBtnTxt" link><span class="text-[#AEAEAE] text-[12px] leading-[20px]">{{ $t('certificate.settingBanner.upload')
        }}</span></el-button>
      </div>
    </el-upload>
  </div>
  <el-image-viewer
    v-if="imgVisible"
    :url-list="[dialogImageUrl]"
    :initial-index="0"
    @close="imgVisible = false"
  />
</template>
<style lang="scss" scoped>
:deep(.el-upload.el-upload--picture-card) {
  width: 62px;
  height: 62px;
  border-radius: v-bind(borderRadius);
  border: 1px solid #DCDFE6;
  background-color: #fff;
}

.upload-icon {
  width: 62px;
  height: 62px;
}
:deep(.el-upload-list.el-upload-list--picture-card) {
  width: 62px;
  height: 62px;

  li {
    width: 62px;
    height: 62px;
    margin: 0;
    border-radius: v-bind(borderRadius);
  }
}

:deep(.el-upload--picture-card) {
  width: 62px;
  height: 62px;
  border-radius: v-bind(borderRadius);
  border: 1px solid #DCDFE6;
  background-color: #fff;
}

:deep(.el-upload-list--picture-card .el-upload-list__item-actions span+span) {
  margin-left: 5px!important;
}
:deep(.el-upload-list--picture-card .el-upload-list__item-actions span) {
  font-size: 14px;
}

.hide-upload-btn :deep(.el-upload--picture-card) {
  display: none !important;
}
</style>
